package com.ouran.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class htmlUtil {
	

	// 根据tag标签转化img 为base64
	public static String imgToBase64(String html, String tag) {
		
		String str = html;
		Document doc = Jsoup.parse(str);
		Elements elements = doc.getElementsByTag(tag);
		System.out.println("这个值呢 ："+elements.size());
		for (int i = 0; i < elements.size(); i++) {
			String strTmp = elements.get(i).toString();
			
			if (strTmp.indexOf("<img src=") > -1) {
				String imgPath = strTmp.substring(strTmp.indexOf("../ueditor/image/"), strTmp.indexOf(".jpg") + 4);
				//hbblock.in
				String imgPathUrl = imgPath.replace("../", ServerUtil.getServerAddress());
				// 读取图片为base64
				
				String base64img = ImageUtil.GetImageStr(imgPathUrl);

				// base替换img src=
				str = str.replace(imgPath, "data:image/jpg;base64," + base64img);
			}
		}
		return str;
	}

	/**
	 * 根据tag标签获取第一个图片base64信息
	 * 
	 * @param html
	 * @param tag
	 * @return
	 */
	public static String getImageBase64(String html, String tag) {
		String str = html;
		String imgBase64 = "";
		Document doc = Jsoup.parse(str);
		Elements elements = doc.getElementsByTag(tag);

		for (int i = 0; i < elements.size(); i++) {
			String strTmp = elements.get(i).toString();
			if (strTmp.indexOf("<img src=") > 0) {
				imgBase64 = strTmp.substring(strTmp.indexOf("data:image/jpg;base64,"), strTmp.indexOf("\" title=\""));
				return imgBase64;
			}
		}
		return imgBase64;
	}

	/**
	 *  获取标题
	 * @param html
	 * @param tag
	 * @return
	 */
	public static String getHtmltitle(String html, String tag) {
		String str = html;
		Document doc = Jsoup.parse(str);
		Elements elements = doc.getElementsByTag(tag);
		return elements.get(0).text();
	}
	
	/**
	 *  获取简易内容
	 * @param html
	 * @param tag
	 * @return
	 */
	public static String getHtmContent(String html, String tag) {
		String str = html;
		Document doc = Jsoup.parse(str);
		Elements elements = doc.getElementsByTag(tag);
		for (int i = 0; i < elements.size(); i++) {
			String strTmp = elements.get(i).toString();
			if (strTmp.indexOf("<p>") > -1) {
				String content = elements.get(i).text();
				if(null == content || "".equals(content)){
					continue;
				}else{
					return content;
				}
			}
		}
		return "";
	}

	public static void main(String[] args) {

		String html = "<h1 label=\"标题居中\" style=\"font-size: 32px; font-weight: bold; border-bottom: 2px solid rgb(204, 204, 204); padding: 0px 4px 0px 0px; text-align: center; margin: 0px 0px 20px;\">&nbsp;&nbsp;&nbsp;&nbsp;ETH价格一路降低<br/></h1><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;据报道：<br/></p><p><img src=\"../ueditor/image/20180929/1538192596246015568.jpg\" title=\"1538141559610092285.jpg\" alt=\"4.jpg\"/></p><p><img src=\"../ueditor/image/20180928/123.jpg\" title=\"123.jpg\" alt=\"4.jpg\"/></p>";

	}

}
